package com.indexingsystem.system.oauth2;

import java.util.Collection;
import java.util.Iterator;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import com.indexingsystem.boss.entity.Pusers;
import com.indexingsystem.system.service.IPusersService;

import org.springframework.jdbc.core.RowMapper;
public class MyAccessDescisionManager implements AccessDecisionManager {
	@Autowired
	private IPusersService iPusersService;
	
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		//第一次验证token会进入  
		String tempUrl = ((FilterInvocation) object).getRequestUrl();
//		System.out.println("用户输入的用户名是：" + authentication.getName());
//		System.out.println("用户输入的密码是：" + authentication.getCredentials());
		final Pusers dhUsers=iPusersService.getDhUsersByName(authentication.getName());
	/*	if (!tempUrl.equals("/") && !tempUrl.equals("/index")) {
			String[] pre = tempUrl.split("/");
			tempUrl = "/" + pre[1] + "/" + pre[2] + "/" + pre[3];
			
			if (authentication.getName().indexOf(pre[2]) <= -1&&!authentication.getName().contains(pre[3])) {
				throw new AccessDeniedException("-------权限认证失败！-------");
			}
		}*/
		/*if (authentication.getName().indexOf(tempUrl) <= -1) {
			throw new AccessDeniedException("-------权限认证失败！-------");
		}*/
		//System.out.println("------------------验证用户是否具有一定的权限------------------");
		if (configAttributes == null)
			return;
		Iterator<ConfigAttribute> it = configAttributes.iterator();
		while (it.hasNext()) {
			String needResource = it.next().getAttribute();
			// authentication.getAuthorities() 用户所有的权限
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needResource.equals(ga.getAuthority())) {
					//System.out.println("------------------用户拥有访问角色------------------");
					return;
				}
			}
		}
		throw new AccessDeniedException("-------无访问权限认证失败！-------");

	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}

}